<?php

namespace App\Models\Goods;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Model;

/**
 * 货品规格模型类
 *
 * @author WangBin
 * @date 2021-09-24
 * @package App\Models\Goods
 */
class Specs extends BaseModel
{
    protected $table = 'b2c_goods_spec';
    protected $primaryKey = 'spec_id';
    protected $casts = [
        'values' => 'array'
    ];

    /**
     * 获取规格列表
     *
     * @param array $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function getByFilter(array $filter = [])
    {
        $specs = Specs::query();
        if(!empty($filter['spec_name'])) {
            $specs->where('spec_name', 'like', '%' . $filter['spec_name'] . '%');
        }
        if(!empty($filter['spec_bn'])) {
            $specs->where('spec_bn', 'like', '%' . $filter['spec_bn'] . '%');
        }
        if(isset($filter['is_active'])) {
            $specs->where('is_active', $filter['is_active']);
        }
        return $specs;
    }

    /**
     * 根据ID获取规格
     *
     * @param int $specId
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function getById(int $specId)
    {
        return Specs::query()->where('spec_id', $specId)->first();
    }

    /**
     * 保存规格
     *
     * @param array $data
     * @return mixed
     */
    public static function saveData(array $data)
    {
        $spec = empty($data['spec_id']) ? new Specs() : Specs::find($data['spec_id']);
        $spec->goods_id = $data['goods_id'];
        $spec->spec_bn = '';
        $spec->name = $data['name'];
        $spec->spec_type = 'text';
        $spec->values = $data['values'];
        return $spec->save() ? $spec->spec_id : 0;
    }

    /**
     * 检查字段值唯一性
     *
     * @param string $field
     * @param string $value
     * @param int $id
     * @return bool
     */
    public static function checkUnique(string $field, string $value, int $id = 0)
    {
        $spec = Specs::query();
        if($id) {
            $spec->where('spec_id', '!=', $id);
        }
        return $spec->where($field, $value)->exists();
    }

    /**
     * 批量删除规格
     *
     * @param array $ids
     * @return mixed
     */
    public static function remove(array $ids)
    {
        return Specs::query()->whereIn('spec_id', $ids)->delete();
    }

    /**
     * 获取货品的规格
     *
     * @param int $goodsId
     * @param array $columns
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getByGoodsId(int $goodsId, array $columns = ['*'])
    {
        $query =  Specs::query()->select($columns)->where('goods_id', $goodsId)->get();
        $query->each(function ($item){
            // 查找规格值
            $item->value_list = SpecValue::getBySpecId($item->spec_id);
        });
        return $query;
    }
}
